package com.lzx.lizhenxing.common.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    // 定义订单超时队列和死信交换机
    public static final String ORDER_DELAY_QUEUE = "order.delay.queue";
    public static final String ORDER_EXCHANGE = "order.exchange";
    public static final String ORDER_DEAD_QUEUE = "order.dead.queue";
    public static final String ORDER_DEAD_ROUTING_KEY = "order.dead";

    // 创建延迟队列（消息过期后转发到死信队列）
    @Bean
    public Queue orderDelayQueue() {
        return QueueBuilder.durable(ORDER_DELAY_QUEUE)
                .withArgument("x-dead-letter-exchange", ORDER_EXCHANGE) // 死信交换机
                .withArgument("x-dead-letter-routing-key", ORDER_DEAD_ROUTING_KEY) // 死信路由键
                .build();
    }

    // 创建死信队列（真正消费的队列）
    @Bean
    public Queue orderDeadQueue() {
        return new Queue(ORDER_DEAD_QUEUE, true);
    }

    // 创建交换机（Direct 类型）
    @Bean
    public DirectExchange orderExchange() {
        return new DirectExchange(ORDER_EXCHANGE);
    }

    // 绑定死信队列到交换机
    @Bean
    public Binding deadBinding() {
        return BindingBuilder.bind(orderDeadQueue())
                .to(orderExchange())
                .with(ORDER_DEAD_ROUTING_KEY);
    }
}